﻿namespace BEGDC.CC.Web.EZVisit.Controls
{
    #region Using Directives

    using System;
    using System.Data;
    using System.Linq;
    using System.Web.UI.WebControls;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using Common;
    using Utility.Extensions;

    #endregion

    public partial class EZVRequestAltAttendee : EZVRequestBaseControl
    {
        protected override void SetVisibility()
        {
            base.SetVisibility();

            this.dgAttendees.Columns[4].Visible = this.Editable;
        }

        protected override void SetViewData()
        {
            this.Session[EZVRequestAttendee.SessionKey + this.SessionKey] = null;
            this.BindAltAttendees();
        }

        protected override bool Validate(out string error)
        {
            error = string.Empty;

            if (this.CurrentActionType.IsNotNullOrWhiteSpace() && this.dgAttendees.Items.Count == 0)
            {
                error = @"- [Escorts ] ALU escorts list were not provided.\n";
            }

            return error.Length == 0;
        }

        public override void Save(EZVisitApplicationTableEntity app)
        {
            if (app == null)
            {
                return;
            }

            app.ALAttNumberOfPerson = this.dgAttendees.Items.Count.ToString();

            base.Save(app);
            this.SaveAltAttendees();
        }

        public void BindAltAttendees()
        {
            if (this.EZVisitApplication == null || !this.Visible)
            {
                return;
            }

            var dt = this.Session[EZVRequestAttendee.SessionKey + this.SessionKey] as DataTable;

            if (dt == null)
            {
                this.Session[EZVRequestAttendee.SessionKey + this.SessionKey] = dt = SetRowID(this.BuildAltAttendeeTable());
            }

            DataView dv = dt.DefaultView;

            dv.RowFilter = "IsEnabled=1";

            this.dgAttendees.DataSource = dv;
            this.dgAttendees.DataBind();

            this.lblTotalEscorts.Text = this.dgAttendees.Items.Count.ToString();
        }

        private void SaveAltAttendees()
        {
            var dt = this.Session[EZVRequestAttendee.SessionKey + this.SessionKey] as DataTable;

            if (dt == null || dt.Rows.Count == 0)
            {
                return;
            }

            var attendees = dt.ToEntities<EZVisitALAttendeeTableEntity>();

            foreach (EZVisitALAttendeeTableEntity attendee in attendees)
            {
                attendee.AppID = this.EZVisitApplication.AppID;

                if (attendee.ALAttendeeIDIsNull())
                {
                    EZVisitALAttendeeManager.Insert(attendee);
                }
                else
                {
                    EZVisitALAttendeeManager.Update(attendee);
                }
            }

            this.Session[EZVRequestAttendee.SessionKey + this.SessionKey] = SetRowID(this.BuildAltAttendeeTable());

            this.BindAltAttendees();
        }

        private DataTable BuildAltAttendeeTable()
        {
            var dt = QueryExtensions.CreateDataTableSchemaFromEntity(typeof(EZVisitALAttendeeTableEntity));

            var appId = this.EZVisitApplication.AppID;

            if (appId != null && appId.Value > 0)
            {
                string condition = string.Format("AppID='{0}' and IsEnabled=1", appId);
                dt = EZVisitALAttendeeManager.SelectByCondition(condition).OfType<EZVisitALAttendeeTableEntity>().ToDataTable();
            }

            dt.Columns.Add("RowId");
            return dt;
        }

        protected void dgAttendees_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
            {
                return;
            }

            var cell = e.Item.Cells[4];

            var btnEdit = (ImageButton)cell.FindControl("btnEdit");
            btnEdit.Attributes.Add("onclick", "return openAttendeePanel('" + e.Item.Cells[0].Text + "');");

            var btnDelete = (ImageButton)cell.FindControl("btnDelete");
            btnDelete.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
        }

        protected void dgAttendees_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            int rowId = Convert.ToInt32(e.Item.Cells[0].Text);

            var dt = (DataTable)this.Session[EZVRequestAttendee.SessionKey + this.SessionKey];

            DataRow row = dt.Rows[rowId - 1];

            if (row.IsNull("ALAttendeeID"))
            {
                dt.Rows.Remove(row);
            }
            else
            {
                row["IsEnabled"] = false;
                row["UpdateAt"] = DateTime.Now;
                row["UpdateBy"] = this.CurrentUser;
            }

            this.Session[EZVRequestAttendee.SessionKey + this.SessionKey] = SetRowID(dt);

            this.BindAltAttendees();
        }

        private static DataTable SetRowID(DataTable table)
        {
            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 1; i <= table.Rows.Count; i++)
                {
                    table.Rows[i - 1]["RowId"] = i.ToString();
                }
            }
            return table;
        }
    }
}